package com.yang.strategy.flter.impl;

import com.yang.common.constant.CacheConstant;
import com.yang.common.constant.RabbitMQConstants;
import com.yang.common.model.StandardSubmit;
import com.yang.common.util.OperatorUtil;
import com.yang.strategy.client.BeaconCacheClient;
import com.yang.strategy.flter.StrategyFilter;
import com.yang.strategy.util.MobileOperatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yangyongsheng
 * @date 2024/9/1 23:54
 * @description
 */
@Service(value = "phase")
@Slf4j
public class PhaseStrategyFilter implements StrategyFilter {
    /**
     * 切分手机号前7位
     */
    private final int MOBILE_START = 0;
    private final int MOBILE_END = 7;

    /**
     * 校验的长度
     */
    private final int LENGTH = 2;

    /**
     * 缓存中分割区域和运营商的标识
     */
    private final String SEPARATE = ",";

    /**
     * 未知的情况
     */
    private final String UNKNOWN = "未知 未知,未知";

    @Autowired
    private BeaconCacheClient cacheClient;

    @Autowired
    private MobileOperatorUtil mobileOperatorUtil;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void strategy(StandardSubmit submit) {
        log.info("【策略模块-号段补全校验】   校验ing…………");
        //1、根据手机号前7位，通过缓存查询手机号信息
        String mobile = submit.getMobile().substring(MOBILE_START, MOBILE_END);
        String mobileInfo = cacheClient.getString(CacheConstant.PHASE + mobile);

        //2.缓存未查到,去查三方接口
        if (StringUtils.isBlank(mobileInfo)) {
            mobileInfo = mobileOperatorUtil.getMobileInfoBy360(mobile);

            if (StringUtils.isNotBlank(mobileInfo)) {
                //调用三方接口后，发送消息到MQ中,让消息平台同步到MYSQL和redis中
                rabbitTemplate.convertAndSend(RabbitMQConstants.MOBILE_AREA_OPERATOR,submit.getMobile());
            } else {
                //三方接口还查询不到,直接就是未知了
                mobileInfo = UNKNOWN;
            }
        }
        //3.对手机号进行解析
        String[] areaAndOperator = mobileInfo.split(SEPARATE);
        if (areaAndOperator.length == LENGTH) {
            submit.setArea(areaAndOperator[0]);
            submit.setOperatorId(OperatorUtil.getOperatorIdByOperatorName(areaAndOperator[1]));
            return;
        }

    }
}
